import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User } from './interfaces/user.interface';
import { CreateUserDto } from './dto/create-user.dto';
import { PasswordService } from 'src/utils/password/password.service';

@Injectable()
export class UsersService {
  constructor(
    @InjectModel('User') private readonly userModel: Model<User>,
    private readonly passwordService: PasswordService,
  ) {}

  /**
   * 根据账号查找指定用户，找到则返回用户
   * @param account 账号
   */
  async findOne(account: string): Promise<User | undefined> {
    return await this.userModel.findOne({ account }).exec();
  }

  /**
   * 创建一个用户，创建成功，则返回创建好的用户
   * @param createUserDto 需要创建的用户
   */
  async createOne(createUserDto: CreateUserDto): Promise<User> {
    // 哈希一下密码
    const password = await this.passwordService.hash(createUserDto.password);
    // 在数据库中创建用户
    const createdUser = new this.userModel({
      account: createUserDto.account,
      password,
    });
    // 返回用户
    return await createdUser.save();
  }
}
